package org.levi.demo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorClient {

    public static void main(String[] args) throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework zkClient = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
        zkClient.start();
        String path = "/watchNode";
        byte[] initData = "initData".getBytes();
        //先创建一个用于事件监听的测试节点
        if (zkClient.checkExists().forPath(path).getVersion() <= 0) {
            zkClient.create().forPath(path, initData);
        }

        //设置监听器
        /*zkClient.getData().usingWatcher(new CuratorWatcher() {
            public void process(WatchedEvent watchedEvent) throws Exception {
                System.out.println("监听到节点事件:" + watchedEvent.getPath());
            }
        }).forPath(path);*/
        NodeCache nodeCache = new NodeCache(zkClient, path);
        nodeCache.getListenable().addListener(() -> System.out.println("节点值已改变...."));
        nodeCache.start();
        //第一次更新
        zkClient.setData().forPath(path, "1".getBytes());
        //第二次更新
        zkClient.setData().forPath(path, "2".getBytes());
        //第三次更新
        zkClient.setData().forPath(path, "3".getBytes());
        //Sleep等待监听事件触发
        Thread.sleep(Integer.MAX_VALUE);
    }
}
